package com.gitee.swsk33.dborder.service.impl;

import com.gitee.swsk33.dbentity.dataobject.Order;
import com.gitee.swsk33.dbentity.dataobject.Product;
import com.gitee.swsk33.dbentity.dataobject.User;
import com.gitee.swsk33.dbentity.model.Result;
import com.gitee.swsk33.dbfeign.feignclient.ProductClient;
import com.gitee.swsk33.dbfeign.feignclient.UserClient;
import com.gitee.swsk33.dborder.dao.OrderDAO;
import com.gitee.swsk33.dborder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDAO orderDAO;

	@Autowired
	private UserClient userClient;

	@Autowired
	private ProductClient productClient;

	@Override
	public Result<Void> add(Order order) {
		Result<Void> result = new Result<>();
		// 先直接插入
		if (orderDAO.insert(order) < 1) {
			result.setResultFailed("插入失败！");
			return result;
		}
		// 插入后，添加与之关联的商品多对多记录
		for (Product each : order.getProducts()) {
			orderDAO.insertRecord(order.getId(), each.getId());
		}
		result.setResultSuccess("插入完成！");
		return result;
	}

	@Override
	public Result<Void> delete(int id) {
		Result<Void> result = new Result<>();
		// 先直接删除
		if (orderDAO.deleteById(id) < 1) {
			result.setResultFailed("删除失败！");
			return result;
		}
		// 然后删除关联部分
		orderDAO.deleteProductIds(id);
		result.setResultSuccess("删除成功！");
		return result;
	}

	@Override
	public Result<Order> getById(int id) {
		Result<Order> result = new Result<>();
		// 先查询订单
		Order getOrder = orderDAO.selectById(id);
		if (getOrder == null) {
			result.setResultFailed("查询失败！");
			return result;
		}
		// 远程调用用户模块，组装订单中的用户对象字段（一对多关联查询）
		User getUser = userClient.getById(getOrder.getUserId()).getData();
		if (getUser == null) {
			result.setResultFailed("查询失败！");
			return result;
		}
		getOrder.setUser(getUser);
		// 远程调用商品模块，组装订单中关联的商品列表（多对多关联查询）
		List<Integer> productIds = orderDAO.selectProductIds(id);
		getOrder.setProducts(productClient.getByBatchId(productIds).getData());
		result.setResultSuccess("查询成功！", getOrder);
		return result;
	}

	@Override
	public Result<List<Order>> getByBatchId(List<Integer> ids) {
		Result<List<Order>> result = new Result<>();
		// 先批量查询
		List<Order> getOrders = orderDAO.selectBatchIds(ids);
		// 组装其中的用户对象字段
		for (Order each : getOrders) {
			each.setUser(userClient.getById(each.getUserId()).getData());
		}
		// 由于批量查询目前专门提供给内部模块作为多对多关联查询时远程调用，因此这里不再对每个对象进行多对多查询，否则会陷入死循环
		result.setResultSuccess("查询完成！", getOrders);
		return result;
	}

}